// yb_mingpian/pages/edit/index.js.js
const recorderManager = wx.getRecorderManager()
const backgroundAudio = wx.getBackgroundAudioManager()
const myaudio = wx.createInnerAudioContext({});

var t = getApp(),
  a = t.requirejs("core"),
  s = t.requirejs("wxParse/wxParse");

let cloud = wx.cloud.init();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cardId: '',
    head_photo: "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1816689961,667730901&fm=26&gp=0.jpg",
    name: '',
    customItem: [],
    detailed: '请选择您的地区',
    region: [],
    address: '',
    phone: "",
    weChat: '',
    email: '',
    introduction: '',
    memberCode: '',
    phoneNumber: '',
    position: '',

    recordingTimeqwe: 0,
    vioce_profile: '',
    cloudUrl: true,
    wall_photo: [],
    clas: false,
    isOpen: false,

    switch1Checked: false,
    shortVideoChecked: false,
    liveChecked: false,

  },
  confim: function () {
    let that = this.data
    let data = {
      uid: t.getCache("userinfo").uid,
      id: that.cardId,
      name: that.name,
      tel: that.phone,
      phone: that.phoneNumber,
      email: that.email,
      head_photo: that.head_photo,
      profile: that.introduction,
      company: that.memberCode,
      position: that.position,
      province: that.region[0],
      city: that.region[1],
      county: that.region[2],
      address: that.address,
      vioce_profile: that.vioce_profile,
      wall_photo: that.wall_photo,
      wechat: that.weChat,
    }
    console.log(data)
    let regExp = (names, title) => {
      if (!data[names]) {
        wx.showToast({
          title,
          icon: 'none',
        })
        return false
      }
      if (names == 'tel' && !/^[1]([3-9])[0-9]{9}$/.test(data[names])) {
        wx.showToast({
          title: '手机号码输入不规范~',
          icon: 'none',
        })
        return false
      }
      return true
    }

    if (!regExp('name', '请输入昵称~')) return
    if (!regExp('tel', '请输入手机号~')) return
    if (!regExp('wechat', '请输入微信号~')) return
    if (!regExp('head_photo', '请选择头像~')) return
    if (!regExp('province', '请选择省份~')) return
    if (!regExp('city', '请选择市~')) return
    if (!regExp('county', '请选择区~')) return
    if (!regExp('address', '请输入详细地址~')) return
    if (!regExp('county', '请输入一段语音~')) return

    if (!data.wall_photo.length) {
      return wx.showToast({
        title: '最少放一张图片~',
        icon: 'none',
      })
    }
    console.log('查看data', data);
    a.post('Card/UpMycard', data, (res) => {
      wx.showToast({
        title: res.info,
        icon: 'none',
        duration: 2000,
      })
      if (res.code == 0) {
        wx.switchTab({
          url: '../card/card',
        });
      }

    })

  },

  inputVmodel: function (e) {
    this.setData({
      [e.target.dataset.names]: e.detail.value
    })
  },

  switch1Change: function () {
    this.setData({
      switch1Checked: !this.data.switch1Checked
    })
  },
  shortVideoChange: function () {
    this.setData({
      shortVideoChecked: !this.data.shortVideoChecked
    })
  },
  liveChange: function () {
    this.setData({
      liveChecked: !this.data.liveChecked
    })
  },
  //省市联动
  bindRegionChange: function (e) {
    var that = this

    this.setData({
      detailed: e.detail.value[0] + " " + e.detail.value[1] + " " + e.detail.value[2],
      region: e.detail.value,
      clas: true
    })
    this.setData({
      "AddSite.area": e.detail.value[0] + " " + e.detail.value[1] + " " + e.detail.value[2]
    })

  },

  chooseImageTap1: function (e) {
    var id = a.pdata(e).id;
    this.upload(this, id, 'chat_pic');
  },
  upload: function (that, field, n) {
    var _this = this;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      itemColor: "#f7982a",
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            _this.chooseWxImage('album', that, field, n)
          } else if (res.tapIndex == 1) {
            _this.chooseWxImage('camera', that, field, n)
          }

        }
      }
    })
  },
  //生成从minNum到maxNum的随机数
  randomNum (minNum, maxNum) {
    switch (arguments.length) {
      case 1:
        return parseInt(Math.random() * minNum + 1, 10);
        break;
      case 2:
        return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
        break;
      default:
        return 0;
        break;
    }
  },
  //录音计时器
  recordingTimer: function () {
    var that = this;
    //将计时器赋值给setInter
    that.data.setInter = setInterval(
      function () {
        var time = that.data.recordingTimeqwe + 1;
        that.setData({
          recordingTimeqwe: time
        })
      }, 1000);
  },
  // 录音授权
  authorize () {
    let that = this;
    wx.authorize({
      scope: 'scope.record',
      success () {
        console.log("录音授权成功");
        // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
        that.openRecording();
      },
      fail () {
        console.log("第一次录音授权失败");
        wx.showModal({
          title: '提示',
          content: '您未授权录音，功能将无法使用',
          showCancel: true,
          confirmText: "授权",
          confirmColor: "#52a2d8",
          success: function (res) {
            if (res.confirm) {
              //确认则打开设置页面（重点）
              wx.openSetting({
                success: (res) => {
                  console.log(res.authSetting);
                  if (!res.authSetting['scope.record']) {
                    //未设置录音授权
                    console.log("未设置录音授权");
                    wx.showModal({
                      title: '提示',
                      content: '您未授权录音，功能将无法使用',
                      showCancel: false,
                      success: function (res) {

                      },
                    })
                  } else {
                    //第二次才成功授权
                    console.log("设置录音授权成功");
                    that.openRecording();
                  }
                },
                fail: function () {
                  console.log("授权设置录音失败");
                }
              })
            } else if (res.cancel) {
              console.log("cancel");
            }
          },
          fail: function () {
            console.log("openfail");
          }
        })
      }
    })
  },
  //开始录音
  openRecording: function () {
    var that = this;
    that.setData({
      recordingTimeqwe: 0,
      isOpen: true,
    })
    const options = {
      duration: 60000, //指定录音的时长，单位 ms，最大为10分钟（600000），默认为1分钟（60000）
      sampleRate: 16000, //采样率
      numberOfChannels: 1, //录音通道数
      encodeBitRate: 96000, //编码码率
      format: 'mp3', //音频格式，有效值 aac/mp3
      frameSize: 50, //指定帧大小，单位 KB
    }
    //开始录音计时   
    that.recordingTimer();
    //开始录音
    recorderManager.start(options);
    recorderManager.onStart(() => {
      console.log('。。。开始录音。。。')
    });
    //错误回调
    recorderManager.onError((res) => {
      console.log(res);
    })
  },

  //结束录音
  shutRecording: function () {
    var that = this;
    that.setData({
      recordingTimeqwe: 0,
      isOpen: false,
    })
    recorderManager.stop();
    recorderManager.onStop((res) => {
      console.log('。。停止录音。。', res.tempFilePath)
      wx.showLoading({
        title: '上传录音中~~~',
        mask: true,
      })
      //结束录音计时  
      clearInterval(that.data.setInter);
      //上传录音
      var timestamp = new Date().getTime()
      wx.cloud.uploadFile({
        cloudPath: 'cloudMusic/' + that.data.cardId + '-' + timestamp + '.mp3',
        filePath: res.tempFilePath,
        // 成功回调
        success: res => {
          console.log('上传录音成功', res)
          wx.hideLoading();
          wx.showToast({
            title: '上传录音成功~'
          })
          let mp3 = res.fileID.substr(res.fileID.lastIndexOf('/'))
          let vioce_profile = "http://7069-pinshang-ztqvr-1301803212.tcb.qcloud.la/cloudMusic" + mp3
          that.setData({
            vioce_profile
          })
        },
        fail: err => {
          console.log(err)
          wx.hideLoading();
          wx.showToast({
            title: '上传失败~',
            icon: 'error'
          })
        }
      })
    })
  },
  // 播放,暂停录音
  playAudio () {
    // let mp3 = this.data.vioce_profile.substr(this.data.vioce_profile.lastIndexOf('/'))
    // var dataUrl = "http://7069-pinshang-ztqvr-1301803212.tcb.qcloud.la/cloudMusic" + mp3
    // var dataUrl = 'cloud://pinshang-ztqvr.7069-pinshang-ztqvr-1301803212/cloudMusic/' + this.data.cardId + 'a.mp3'
    myaudio.src = this.data.vioce_profile;
    // this.setData({
    //   cloudUrl: !this.data.cloudUrl
    // })
    // if (!this.data.cloudUrl) {
    myaudio.play();
    // } else {
    //   myaudio.stop()
    //   this.setData({
    //     cloudUrl: true
    //   })
    // }
  },

  chooseImages () {
    var _this = this,
      site = getApp().siteInfo,
      url = site.siteroot + '?i=' + site.uniacid + '&t=undefined&v=' + site.version + '&from=wxapp&c=entry&a=wxapp&do=index_uploadFile&path=chat_pic&m=yb_mingpian&sign=5201314';
    wx.chooseImage({
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'],
      success: function (res) {
        let file = res.tempFilePaths
        console.log('查看图片', file)
        wx.showLoading({
          title: '上传图片中~请稍后~',
          mask: true,
        })
        for (var i = 0; i < file.length; i++) {
          wx.uploadFile({
            url: url,
            filePath: file[i],
            name: 'file_upload',
            success: (res) => {
              console.log('查看上传后的', res)
              if (res.data != null && res.data != '') {
                _this.setData({
                  wall_photo: [..._this.data.wall_photo, res.data]
                })
              } else {
                a.error('上传失败，请重试')
              }
            }
          });
        }
        wx.hideLoading();
        wx.showToast({
          title: '上传成功~',
        })
      }
    });
  },
  deleteImg (e) {
    this.data.wall_photo.splice(e.currentTarget.dataset.index, 1)
    // let wall_photo = this.data.wall_photo.filter(item => item != a)
    this.setData({
      wall_photo: this.data.wall_photo
    })
  },
  chooseWxImage: function (type_, that, field, n) {
    var _this = this,
      site = getApp().siteInfo,
      url = site.siteroot + '?i=' + site.uniacid + '&t=undefined&v=' + site.version + '&from=wxapp&c=entry&a=wxapp&do=index_uploadFile&path=' + n + '&m=yb_mingpian&sign=5201314';
    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: [type_],
      success: function (res) {
        console.log(res)
        wx.uploadFile({
          url: url,
          filePath: res.tempFilePaths[0],
          name: 'file_upload',
          success: function (res) {

            if (res.data != null && res.data != '') {
              console.log(res.data)
              that.setData({
                head_photo: res.data,
              })
              // that.bindconfirm();
            } else {
              a.error('上传失败，请重试')
            }
          }
        })

      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  // 进来获取内容编辑 应该根据名片id获取内容 而不是根据uid吧
  getCard () {
    let that = this
    a.get("card/getMycard", { uid: t.getCache("userinfo").uid, }, function (e) {
      console.log("四年", e)
      e = e.info
      that.setData({
        name: e.user_name,
        phone: e.tel,
        phoneNumber: e.phone,
        email: e.email,
        head_photo: e.head_photo,
        introduction: e.profile,
        memberCode: e.company,
        position: e.position,
        address: e.address,
        vioce_profile: e.vioce_profile,
        wall_photo: e.wall_photo ? e.wall_photo.split(',') : [],
        weChat: e.wechat_number,
      })
      if (e.province && e.city && e.county) {
        that.setData({
          detailed: e.province + " " + e.city + " " + e.county,
          customItem: [e.province, e.city, e.county],
          region: [e.province, e.city, e.county],
          clas: true
        })
      }
    })
  },
  onLoad: function (options) {
    this.setData({
      cardId: options.id
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.getCard();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})